/**
 * Created by txh on 2019/7/10.
 */
import React,{Component} from 'react'
import { Alert,Icon,Popover,Table, Button ,Modal,Tooltip,Tag, Tabs} from 'antd';
import {getPageSize, getPageStartIndex} from "../util/WtTableCommon";
import './WtBooks.css'
import WtSearchBooks from "./WtSearchBooks";
import WtBookDetailsModal from "./WtBookDetailsModal";
import WtHostPost from "../util/WtHostPost";
import WtNotification from "../util/WtNotification";

const { confirm } = Modal;

class WtBooksTable extends Component{
    constructor(props){
        super(props)
        this.state={
            selectedRowKeys: [], // Check here to configure the default column
            loading: false,
            pagination:{showSizeChanger:false,pageSizeOptions:['10','20','50','100'],current:1},
            data:[],
            bookInfo:null,
            changeVisible:false,
            tabIndex : '1',
            detailVisible: false,
            searchValue : '',
            value:null,
        }
        this.colsKey={
        state : {
                title:'在馆状态',
                key:'#',
                width:20,
                render:(text,record)=>{
                    return (
                        record.isNum > 0 ?
                            <Tag className="wt-tag-shadow" color="#87d068" style={{width: 40}}/>
                            :
                            <Tag className="wt-tag-shadow" color="#999db1" style={{width: 40}}/>

                    )
                }
            },
            isbn:{
                title:'ISBN码',
                key:'isbn',
                width:100,
                render:(text,record)=>{
                    return (
                        record.isbn
                    )
                }
            },
            bookType:{
                title:'图书类型',
                key:'bookType',
                width:100,
                render:(text,record)=>{
                    return (
                        record.bookType
                    )
                }
            },
            bookName:{
                title:'图书名称',
                key:'bookName',
                width:100,
                render:(text,record)=>{
                    return (
                        record.bookName
                    )
                }
            },
            authorName:{
                title:'作者名称',
                key:'authorName',
                width:100,
                render:(text,record)=>{
                    return (
                        record.authorName
                    )
                }
            },
            publisher:{
                title:'出版社',
                key:'publisher',
                width:100,
                render:(text,record)=>{
                    return (
                        record.publisher
                    )
                }
            },
            date:{
                title:'日期',
                key:'date',
                width:100,
                render:(text,record)=>{
                    return (
                        record.date
                    )
                }
            },
            totalNum:{
                title:'总数量',
                key:'totalNum',
                width:90,
                render:(text,record)=>{
                    return (
                        record.totalNum
                    )
                }
            },
            isNum:{
                title:'在馆数量',
                key:'isNum',
                width:90,
                render:(text,record)=>{
                    return (
                        record.isNum
                    )
                }
            },
            price:{
                title:'价格',
                key:'price',
                width:80,
                render:(text,record)=>{
                    return (
                        record.price
                    )
                }
            },
            operation:{
                title:'操作',
                key:'operation',
                width:110,
                render:(text,record)=>{
                    return (
                        <div className="operation">
                            <Tooltip title="图书借阅">
                                <a className="operation-button" onClick={()=>{this.handleBooksBorrow(record)}}>借阅</a>
                            </Tooltip>
                            <span>|</span>
                            <Tooltip title="查看详情">
                                <a className="operation-button" onClick={()=>{this.handelBookDetailModal(record)}}>查看</a>

                            </Tooltip>
                        </div>
                    )}},
        }
    }
    //界面初始化
    componentDidMount() {
        this.handleRefresh();
    }

    //处理图书借阅
    handleBooksBorrow (record){
        if (record.isNum <= 0){
            WtNotification.error("该书籍已被借空");
            return;
        }
        confirm({
            title: '借阅确认',
            content: "你确定要借阅这本书吗？",
            onOk : ()=>{
                WtHostPost("/borrow",{isbn:record.isbn},true).then(({json}) => {
                    if (json.code === 0){
                        this.handleRefresh();
                    }else {
                        throw json;
                    }
                }).catch(err=>{
                    WtNotification.error(err.msg);
                })
            },
        })
    };

    //fetch 函数去后台取数据，数据的格式是json格式
    fetch=(params={})=>{
        params['type'] = parseInt(this.state.tabIndex);
        params['search'] = this.state.searchValue;
        this.setState({loading:true});
        WtHostPost("/book-get",{...params},true).then(({json}) => {
            if (json.code === 0){
                this.setState({data:json.data})
                let pagination = this.state.pagination;
                pagination.total = json.total;
                this.setState({pagination,loading:false});
            }else {
                throw json;
            }
        }).catch(err=>{
            WtNotification.error("添加订单失败");
            this.setState({loading:false});
        })
    }


//界面有刷新的时候
    handleRefresh = ()=>{
        let offset =getPageStartIndex(this.state.pagination);
        let limit = getPageSize(this.state.pagination)
        this.fetch({offset,limit})
    }

    handleTableChange=(key)=> {
        console.log(key);
        this.setState({tabIndex:key},()=>{
            this.handleRefresh()
        })
    }

    getColumns=()=>{
        let cols=[];
        cols.push(this.colsKey.state)
        cols.push(this.colsKey.isbn);
        cols.push(this.colsKey.bookType);
        cols.push(this.colsKey.bookName);
        cols.push(this.colsKey.authorName);
        cols.push(this.colsKey.publisher);
        cols.push(this.colsKey.date);
        cols.push(this.colsKey.totalNum);
        cols.push(this.colsKey.isNum);
        cols.push(this.colsKey.price);
        cols.push(this.colsKey.operation);
        return cols;
    };

    onSearchChange = selectedRowKeys => {
        this.setState({ selectedRowKeys });
    };

    handleSearch = (value) => {
        this.setState({searchValue:value},()=>{
            this.handleRefresh();
        })
    }


    handleBookDetailOk=(value)=>{
        this.setState({detailVisible:value})
    }


    handelBookDetailModal=(item)=>{
        this.setState({detailVisible:true,value:item})
    }


    renderDataContainers(){
        const {selectedRowKeys} = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSearchChange,
        };
        return(
            <div>
                <div style={{marginTop:10}}>
                    <div style={{textAlign:'right',marginBottom:10}} className="content-col">
                        <span><Tooltip title="在馆"><Tag className="wt-tag-shadow" color="#87d068" style={{width: 40}}/></Tooltip> <span>在馆</span></span>
                        <span><Tooltip title="借空"><Tag className="wt-tag-shadow" color="#999db1" style={{width: 40}}/></Tooltip> <span>借空</span></span>
                    </div>
                    <Alert style={{marginBottom: 11,marginTop:18}}
                        message={
                            <span>
                                你选中了{this.state.selectedRowKeys.length}条数据(
                                <a onClick={() => {this.setState({selectedRowKeys:[]})}}>重选</a>),
                                <span style={{float:'right'}}>
                                    <a onClick={this.handleRefresh} style={{padding:'0 6px'}}>刷新</a>
                                </span>
                            </span>
                        }
                        type="info"
                        icon={<Icon type="info-circle" />}
                    />
                    <Table style={{textAlign:'center'}}
                        size="small"
                        columns={this.getColumns()}
                        rowSelection={rowSelection}
                        rowKey={record => record.isbn}
                        dataSource={this.state.data}
                        pagination={this.state.pagination}
                        loading={this.state.loading}
                        onChange={this.handleTableChange}
                    />
                </div>
            </div>
        )
    }


    render() {
        const { TabPane } = Tabs;
        return (
            <div>
                <h2>图书查询</h2>
                <Tabs value={this.state.tabIndex} onChange={this.handleTableChange}>
                    <TabPane tab="全部图书" key="1"/>
                    <TabPane tab="在馆图书" key="2"/>
                    <TabPane tab="借出图书" key="3"/>
                </Tabs>
                <WtSearchBooks
                    handleSearch={this.handleSearch}/>
                {this.renderDataContainers()}
                <WtBookDetailsModal
                    showBookDetailModal={this.handelBookDetailModal}
                    detailVisible={this.state.detailVisible}
                    value={this.state.value}
                    handleBookDetailOk={this.handleBookDetailOk}
                />

            </div>
        );
    }
}



export default WtBooksTable;
